<template>
  <div class="orders-container">
    <div class="search-form">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.status" placeholder="全部状态">
            <el-option label="待付款" :value="1" />
            <el-option label="待发货" :value="2" />
            <el-option label="已发货" :value="3" />
            <el-option label="已完成" :value="4" />
            <el-option label="已关闭" :value="5" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单号">
          <el-input v-model="searchForm.orderId" placeholder="请输入订单号" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table :data="orderList" v-loading="loading" border>
      <el-table-column prop="orderId" label="订单号" width="120" />
      <el-table-column prop="payment" label="实付金额">
        <template #default="{ row }">
          ¥{{ row.payment }}
        </template>
      </el-table-column>
      <el-table-column label="订单状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column prop="buyerNick" label="买家昵称" />
      <el-table-column label="操作" width="250">
        <template #default="{ row }">
          <el-button
            v-if="row.status === 3"
            type="primary"
            link
            @click="handleShip(row)"
          >发货</el-button>
          <el-button
            v-if="row.refundStatus === 1"
            type="warning"
            link
            @click="handleRefund(row)"
          >处理退款</el-button>
          <el-button type="info" link @click="handleDetail(row)">订单详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      class="pagination"
      v-model:current-page="page"
      v-model:page-size="pageSize"
      :total="total"
      @current-change="getOrderList"
    />

    <!-- 发货对话框 -->
    <el-dialog
      title="订单发货"
      v-model="shipDialogVisible"
      width="400px"
    >
      <el-form :model="shipForm" label-width="100px">
        <el-form-item label="快递公司">
          <el-select v-model="shipForm.deliveryId" placeholder="请选择快递公司">
            <el-option
              v-for="item in deliveryCompanies"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="shipDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitShip">确定</el-button>
      </template>
    </el-dialog>

    <!-- 订单详情对话框 -->
    <el-dialog
      title="订单详情"
      v-model="detailDialogVisible"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单号">{{ currentOrder.orderId }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <el-tag :type="getStatusType(currentOrder.status)">
            {{ getStatusText(currentOrder.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="实付金额">¥{{ currentOrder.payment }}</el-descriptions-item>
        <el-descriptions-item label="支付方式">
          {{ currentOrder.paymentType === 1 ? '在线支付' : '货到付款' }}
        </el-descriptions-item>
        <el-descriptions-item label="买家">{{ currentOrder.buyerNick }}</el-descriptions-item>
        <el-descriptions-item label="买家留言">{{ currentOrder.buyerMessage || '无' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentOrder.createTime }}</el-descriptions-item>
        <el-descriptions-item label="付款时间">{{ currentOrder.paymentTime || '未付款' }}</el-descriptions-item>
        <el-descriptions-item label="发货时间">{{ currentOrder.consignTime || '未发货' }}</el-descriptions-item>
        <el-descriptions-item label="完成时间">{{ currentOrder.endTime || '未完成' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

// 数据状态
const loading = ref(false)
const orderList = ref([])
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索表单
const searchForm = ref({
  status: '',
  orderId: ''
})

// 发货对话框
const shipDialogVisible = ref(false)
const shipForm = ref({
  orderId: '',
  deliveryId: ''
})
const deliveryCompanies = ref([])

// 详情对话框
const detailDialogVisible = ref(false)
const currentOrder = ref({})

// 获取订单列表
const getOrderList = async () => {
  loading.value = true
  try {
    const res = await axios.get('/orders/list', {
      params: {
        page: page.value,
        pageSize: pageSize.value,
        status: searchForm.value.status,
        orderId: searchForm.value.orderId
      }
    })
    orderList.value = res.data
    total.value = res.data.total
  } catch (error) {
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 获取状态标签类型
const getStatusType = (status) => {
  const statusMap = {
    1: 'info', // 待付款
    2: 'warning', // 已付款
    3: 'primary', // 未发货
    4: 'success', // 已发货
    5: 'danger', // 交易成功
    6: 'danger' // 交易关闭
  }
  return statusMap[status]
}

// 获取状态文字
const getStatusText = (status) => {
  const statusMap = {
    1: '未付款',
    2: '已付款',
    3: '未发货',
    4: '已发货',
    5: '交易成功',
    6: '交易关闭'
  }
  return statusMap[status]
}

// 处理发货
const handleShip = async (row) => {
  // 获取快递公司列表
  try {
    const res = await axios.get('/logic/item/delivery-companies')
    deliveryCompanies.value = res.data
  } catch (error) {
    ElMessage.error('获取快递公司列表失败')
    return
  }

  shipForm.value = {
    orderId: row.orderId,
    deliveryId: ''
  }
  shipDialogVisible.value = true
}

// 提交发货
const submitShip = async () => {
  try {
    await axios.post('/logic/item/select-delivery', null, {
      params: {
        orderId: shipForm.value.orderId,
        deliveryId: shipForm.value.deliveryId
      }
    })
    await axios.post(`/logic/item/order/ship/${shipForm.value.orderId}`)
    ElMessage.success('发货成功')
    shipDialogVisible.value = false
    getOrderList()
  } catch (error) {
    ElMessage.error('发货失败')
  }
}

// 处理退款
const handleRefund = async (row) => {
  try {
    await ElMessageBox.confirm('确认处理退款申请？')
    await axios.post(`/logic/item/order/refund/${row.orderId}`)
    ElMessage.success('退款处理成功')
    getOrderList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('退款处理失败')
    }
  }
}

// 查看订单详情
const handleDetail = async (row) => {
  try {
    const res = await axios.post(`/orders/${row.orderId}`)
    // 检查响应数据
    console.log('订单详情数据:', res.data)

    if (res.data) {
      // 确保响应数据正确赋值给 currentOrder
      currentOrder.value = {
        orderNo: row.orderId, // 订单号
        payment: res.data.payment, // 支付金额
        paymentType: res.data.paymentType, // 支付类型
        status: res.data.status, // 订单状态
        createTime: res.data.createTime, // 创建时间
        updateTime: res.data.updateTime, // 更新时间
        paymentTime: res.data.paymentTime, // 支付时间
        consignTime: res.data.consignTime, // 发货时间
        endTime: res.data.endTime, // 结束时间
        shippingName: res.data.shippingName, // 物流公司
        shippingCode: res.data.shippingCode, // 物流单号
        buyerMessage: res.data.buyerMessage, // 买家留言
        postFee: res.data.postFee // 邮费
      }

      // 打开对话框
      detailDialogVisible.value = true
    } else {
      ElMessage.warning('未获取到订单详情')
    }
  } catch (error) {
    console.error('获取订单详情错误:', error)
    ElMessage.error('获取订单详情失败')
  }
}

// 搜索
const handleSearch = () => {
  page.value = 1
  getOrderList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    status: '',
    orderId: ''
  }
  page.value = 1
  getOrderList()
}

onMounted(() => {
  getOrderList()
})
</script>

<style scoped>
.orders-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
